package com.cq.hd.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cq.hd.member.api.dto.MerchantBankCardDto;
import com.cq.hd.member.api.vo.MerchantBankCardVo;
import com.cq.hd.member.mapper.TbMerchantBankCardMapper;
import com.cq.hd.member.po.TbMerchantBankCardPo;
import com.cq.hd.member.service.TbMerchantBankCardService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @author much
 * @since 2024/04/16 17:00
 */
@Service
public class TbMerchantBankCardServiceImpl implements TbMerchantBankCardService {

    @Resource
    private TbMerchantBankCardMapper merchantBankCardMapper;

    @Override
    public void saveBankCard(MerchantBankCardDto merchantBankCardDto) {
        TbMerchantBankCardPo bankCardPo = getByMerchantId(merchantBankCardDto.getMerchantId());
        if (bankCardPo == null) {
            bankCardPo = BeanUtil.copyProperties(merchantBankCardDto, TbMerchantBankCardPo.class);
            bankCardPo.setCreateTime(LocalDateTime.now());
            bankCardPo.setUpdateTime(LocalDateTime.now());
            merchantBankCardMapper.insert(bankCardPo);
        } else {
            bankCardPo.setBankCode(merchantBankCardDto.getBankCode());
            bankCardPo.setBankName(merchantBankCardDto.getBankName());
            bankCardPo.setCardName(merchantBankCardDto.getCardName());
            bankCardPo.setCardNo(merchantBankCardDto.getCardNo());
            bankCardPo.setUpdateTime(LocalDateTime.now());
            merchantBankCardMapper.updateById(bankCardPo);
        }
    }

    @Override
    public MerchantBankCardVo getBankCardByMerchantId(Long merchantId) {
        LambdaQueryWrapper<TbMerchantBankCardPo> eq = Wrappers.<TbMerchantBankCardPo>lambdaQuery()
                .eq(TbMerchantBankCardPo::getMerchantId, merchantId);
        TbMerchantBankCardPo tbMerchantBankCardPo = merchantBankCardMapper.selectOne(eq);
        if (tbMerchantBankCardPo != null) {
            return BeanUtil.copyProperties(tbMerchantBankCardPo, MerchantBankCardVo.class);
        }
        return null;
    }

    private TbMerchantBankCardPo getByMerchantId(Long merchantId) {
        LambdaQueryWrapper<TbMerchantBankCardPo> eq = Wrappers.<TbMerchantBankCardPo>lambdaQuery()
                .eq(TbMerchantBankCardPo::getMerchantId, merchantId);
        return merchantBankCardMapper.selectOne(eq);
    }

}
